package com.niiwoo.civet.account.listener;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.constant.MQConstant;
import com.niiwoo.civet.account.dao.entity.TransFreezeOrder;
import com.niiwoo.civet.account.dto.request.TransFreezeRequestDTO;
import com.niiwoo.civet.account.dto.response.TransFreezeResponseDTO;
import com.niiwoo.civet.account.service.local.trade.TransFreezeLocalService;
import com.niiwoo.civet.account.service.local.trade.TransOrderFacade;
import com.niiwoo.civet.base.enums.CommonResultEnum;
import com.niiwoo.civet.trade.constant.MqConstant;
import com.niiwoo.civet.trade.dto.common.RefundFreezeResultMsgDTO;
import com.niiwoo.tripod.provider.exception.BizException;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created by wangjichao on 2018/4/25.
 */

@Slf4j
@Component
public class RefundFreezeListener {

    @Autowired
    private TransOrderFacade transOrderFacade;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private TransFreezeLocalService transFreezeLocalService;

    @RabbitListener(queues = {MQConstant.REFUND_FREEZE_QUEUE})
    public void refundFreeze(TransFreezeRequestDTO transFreezeRequestDTO, Message message, Channel channel){
        log.info("还款垫付冻结消息:{}", JSON.toJSONString(transFreezeRequestDTO));
        try{
            TransFreezeResponseDTO responseDTO = transOrderFacade.refundFreeze(transFreezeRequestDTO);
            log.info("还款垫付冻结消息处理结果：{}",JSON.toJSONString(responseDTO));
        }catch (BizException e){
            log.error("还款垫付冻结消息消费BizException:{}",JSON.toJSONString(transFreezeRequestDTO),e);
            if("ACC10007".equals(e.getErrorCode())){
                log.info("还款垫付消息消息处理余额不足，进入冻结失败通知流程：{}",JSON.toJSONString(transFreezeRequestDTO));
                TransFreezeOrder transFreezeOrder = transFreezeLocalService.queryTransFreezeOrderByIdAndType(transFreezeRequestDTO.getOrderId(),transFreezeRequestDTO.getOrderType());
                if(transFreezeOrder != null){
                    transFreezeLocalService.freezeFailure(transFreezeOrder.getId(),"ACC10007","账户余额不足");
                }else{
                    log.info("还款垫付消息消息处理余额不足，查询无订单：{}",JSON.toJSONString(transFreezeRequestDTO));
                }
            }
        } catch(Exception e){
            log.error("还款垫付冻结消息消费异常:{}",JSON.toJSONString(transFreezeRequestDTO),e);
        }finally {
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                log.error("还款垫付冻结消息应答异常：{}",JSON.toJSONString(transFreezeRequestDTO),e);
            }
        }
    }
}
